package com.cms.admin.action.employee;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import net.sf.json.JSONObject;

import com.cms.admin.action.BaseAction;
import com.cms.admin.model.City;
 
import com.cms.admin.model.DepartmentList;
import com.cms.admin.model.DepartmentListExt;
 
import com.cms.admin.model.PageBean;
 
import com.cms.admin.service.common.TemplateService;
import com.cms.admin.service.employee.DepartmentListService;
import com.cms.admin.service.privilege.CityService;
import com.cms.admin.util.Constants;
import com.cms.admin.util.Util;
import com.opensymphony.xwork2.ModelDriven;

public class DepartmentManagerAction extends BaseAction implements ModelDriven<DepartmentListExt>{

	private TemplateService templateService;
	
	private DepartmentListService departmentService;
	
	private List<DepartmentList> departmentList;
	
	private PageBean page;
	
	private DepartmentListExt search = new DepartmentListExt();
	
	private String res;

	private DepartmentList department;
	

	private CityService orgService;
	
	

	private  ArrayList<City>  organizationList ;
	
	public String updateDepartmentById()
	{
		
		 

		departmentService.updateByPrimaryKey(department);
		return SUCCESS;	
		
		
	}
	public String deleteDepartmentById()
	{
		
		 

		search = getSearch();

		//departmentService.deleteByPrimaryKey(search.getDeptNo());
		return SUCCESS;	
		
		
	}

	public String getDepartmentById()
	{
		
		search = getSearch();
	//	LOG.debug("department :"+search.getDeptNo());
		//department = departmentService.selectByPrimaryKey(search.getDeptNo());
		organizationList = orgService.selectAllOrg();
	//	LOG.debug("department :"+department.getDeptLocation());

		return SUCCESS;	
		
		
	}
 
	 
	public String preAddDepartment()
	{
		
		organizationList = orgService.selectAllOrg();
		
		return SUCCESS;
	}
 
	public String addDepartment()
	{
		
		int num = departmentService.insert(department);
		
 
		return SUCCESS;
		
	}
	

 
	public String queryDepartmentList()
	{ 
		try 
		{
		
		LOG.info("Start MemberAction process,method is queryMemberList");

		// ����ͨ��Ajax��param1=value���ַ�ʽ���ݵĲ����������ModelDriven�͵�search������
		search = getSearch();

		LOG.debug("Action is:" + search.getAction());
		page = new PageBean(search.getCurrentPage(), search.getPageSize());

		//search.setDeptNos(deptNos);
		departmentList = departmentService.selectByCondition(page,search);
		organizationList = orgService.selectAllOrg();
	
			res = this.getQueryResult(departmentList, organizationList,page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res=Constants.INFO_SYS_ERROR;
			return ERROR;
		}
		
		return SUCCESS;
		
	}
	
	
	/**
	 * �������б�
	 */
	private String getQueryResult(List<DepartmentList> departmentList, List<City> organizationList,PageBean page)
			throws Exception {
		HashMap map = new HashMap();
		map.put("departmentList", departmentList);
		map.put("organizationList", organizationList);
		map.put("page", page);
		 
		String result = "";
		result = templateService.generateContentByFreeMarker(
				Constants.TEMPLATE_DEPTMENT_LIST_QUERY_RESULT, map);
		return result;
	}
	
	public String ajaxQueryDepartmentList()
	{
		try {
			LOG.info("Start TradeDetailAction process,method is ajaxQueryRechargeList");

			// ����ͨ��Ajax��param1=value���ַ�ʽ���ݵĲ����������ModelDriven�͵�search������
			search = getSearch();

			LOG.debug("Action is:" + search.getAction());
		 
			LOG.debug("Condition1:" + search.getCondition1());
			LOG.debug("Condition2:" + search.getCondition2());
			LOG.debug("Condition3:" + search.getCondition3());
			 			
			page = new PageBean(search.getCurrentPage(), search.getPageSize());
			//search.setDeptNos(deptNos);
		   //��ѯ���ż�¼
			departmentList = departmentService.selectByCondition(page, search);

			organizationList = orgService.selectAllOrg();
			//String res = this.getQueryResult(departmentList, organizationList,page);
			JSONObject o = new JSONObject();

			o.put("pageCount", page.getTotalPage());
			o.put("content", res);

			return ajaxJsonSuccessMessage(o);

		} catch (Exception e) {

			e.printStackTrace();
			return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
		}

		
	}


 
	
	 


	/**
	 * @return the search
	 */
	public DepartmentListExt getSearch() {
		return search;
	}



	/**
	 * @param search the search to set
	 */
	public void setSearch(DepartmentListExt search) {
		this.search = search;
	}
	
	/**
	 * @return the templateService
	 */
	public TemplateService getTemplateService() {
		return templateService;
	}

	/**
	 * @param templateService the templateService to set
	 */
	public void setTemplateService(TemplateService templateService) {
		this.templateService = templateService;
	}
	
	/**
	 * @return the res
	 */
	public String getRes() {
		return res;
	}

	/**
	 * @param res the res to set
	 */
	public void setRes(String res) {
		this.res = res;
	}

	

 

	public void exportCSV()
	{ 
		try 
		{
		
		LOG.info("Start MemberAction process,method is exportCSV");

		// ����ͨ��Ajax��param1=value���ַ�ʽ���ݵĲ����������ModelDriven�͵�search������

		LOG.debug("Action is:" + search.getAction());

		departmentList = departmentService.getAllRows();
		organizationList = orgService.selectAllOrg();
		HttpServletResponse response = ServletActionContext.getResponse();
		Map<String,String> map = getOrgName(organizationList);
		
		createCSVFile(departmentList,map, "�ŵ��б�.CSV", response);
	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			res=Constants.INFO_SYS_ERROR;
		}
		
		
	}
	
	
	public Map<String,String> getOrgName(ArrayList<City> organizationList) {
		
		Map<String,String> map = new HashMap<String, String>();
		int size = organizationList.size();
		for (int i = 0; i < size; i++) {
			City org = organizationList.get(i);
			//map.put(org.getOrgId(), org.getName());
		}
		return map;
	}
	
	 public  void createCSVFile(List<DepartmentList> exportData, Map<String,String> orglist, String filename ,HttpServletResponse response) throws IOException {
	    	ServletOutputStream outSTr = null;
			response.reset();// ��������   
			response.setHeader("Content-disposition", "attachment; filename=" +Util.toUtf8String(filename));// �趨����ļ�ͷ   
			response.setContentType("csv/plain");// һ�����йؼ�������
			BufferedOutputStream buff = null;
			StringBuffer write = new StringBuffer();
			String enter = "\r\n";
			
	        try {
	        	outSTr = response.getOutputStream();// ����
				buff = new BufferedOutputStream(outSTr);

	            // д���ļ�����
	            int size = exportData.size();
	            
	            write.append("\""+"���ű��"+ "\"");
	        	write.append(",");  
	        	write.append("\""+"���ż��"+  "\"");
	        	write.append(",");  
	        	write.append("\""+"����ȫ��"+ "\"");
	        	write.append(",");  
	        	write.append("\""+"����λ��"+  "\"");
	        	write.append(",");  
	        	write.append("\""+"����"+  "\"");
	        	write.append(",");  
	        	write.append("\""+"������"+  "\"");
	        	write.append(",");  
	        	write.append("\""+"�����˵绰"+  "\"");
	        	write.append(",");  
	        	write.append("\""+"�ŵ�绰"+  "\"");
	        	write.append(",");  
	        	write.append("\""+"����˵��"+  "\"");
	        	write.append(enter); 
	            for (int i = 0; i < size; i++) {
	            	DepartmentList dep = exportData.get(i);
	            	//write.append("\""+dep.getDeptNo()+ "\"");
	            	write.append(",");  
	            	//write.append("\""+dep.getDeptName()+ "\"");
	            	write.append(",");  
	            	//write.append("\""+dep.getDeptLongName()+ "\"");
	            	write.append(",");  
	            	//write.append("\""+dep.getDeptLocation() + "\"");
	            	write.append(",");  
	            	//write.append("\""+(null == dep.getDeptAreano()?"":orglist.get(dep.getDeptAreano())) + "\"");
	            	write.append(",");  
	            //write.append("\""+dep.getDeptMajor() + "\"");
	            	//write.append(",");  
	            	//write.append("\""+dep.getDeptMajorPhone() + "\"");
	            	write.append(",");  
	            	//write.append("\""+(null == dep.getDeptTel()?"":dep.getDeptTel()) +"\"");
	            	write.append(",");  
	            	//write.append("\""+(null == dep.getDeptNote()?"":dep.getDeptNote()) +"\"");
	            	write.append(enter); 
				}
	             
	            buff.write(write.toString().getBytes("GBK"));
				buff.flush();
				buff.close();
	        } catch (Exception e) {  
	           e.printStackTrace();  
	        } finally {  
				buff.flush();
				buff.close(); 
	       }  
	    }
	@Override
	public DepartmentListExt getModel() {
		// TODO Auto-generated method stub
		return null;
	}

}
